#[post("/library/upload_dub_file", data = "<data>")]
fn upload_dub_file(cookies: Cookies, data: Data) -> String {
    let user_info: UserInfo = get_cookies(&cookies);
    if user_info.id == 0 {
        return "fail:您未登录，请先登录".to_string();
    }

    let mut file_hostr: HoString = HoString::new();
    file_hostr.push_bytes(data.peek());
    let file_info: Vec<HoString> = file_hostr.split_bytes("\n".as_bytes());
    let file_name_op: Option<&HoString> = file_info.get(7);
    let mut file_name: HoString = HoString::new();
    if let Some(f) = file_name_op {
        let file_name_u8: &[u8] = f.trim();
        file_name.push_bytes(file_name_u8);
    } else {
        return "fail:Data数据不合法".to_string();
    }
    let file_name_array: Vec<HoString> = file_name.split_bytes(".".as_bytes());
    let file_name_array_len: usize = file_name_array.len() - 1;
    let file_extra_name: &HoString = file_name_array.get(file_name_array_len).unwrap();
    let now: SystemTime = SystemTime::now();
    let since_epoch_res = now.duration_since(UNIX_EPOCH);
    let since_epoch: Duration;
    if let Ok(d) = since_epoch_res {
        since_epoch = d;
    } else {
        return "fail:时间戳获取失败".to_string();
    }
    let timestamp = since_epoch.as_millis();
    let upload_name: String = format!("uploads/{}.{}", timestamp, file_extra_name.to_str());
    if let Ok(_) = data.stream_to_file(upload_name.as_str()) {
        let u8_vec: Vec<u8> = HoFile::read_file_u8vec(upload_name.as_str());
        let mut bytes: HoBytes = HoBytes::new();
        bytes.push_bytes(u8_vec.as_slice());
        let u8_vec_vec: Vec<Vec<u8>> = bytes.split_byte('\n' as u8);
        let mut content: HoBytes = HoBytes::new();
        for i in 24..u8_vec_vec.len() - 1 {
            match u8_vec_vec.get(i) {
                Some(v) => content.push_bytes(v.as_slice()),
                None => break
            }
        }
        HoFile::write_file_bytes(upload_name.as_str(), content.to_bytes());
        return format!("success:{}.{}", timestamp, file_extra_name.to_str());
    } else {
        return "fail:文件移动失败".to_string();
    }
}

#[derive(FromForm)]
struct AcceptCopywrite {
    id: usize,
    topic_type: String,
    file_list: String
}

#[post("/library/accept_copywrite_order", data = "<form>")]
fn accept_copywrite_order(form: Form<AcceptCopywrite>, _cookies: Cookies, state: State<MySqlDriver>) -> String {
    let pool_result: Result<Pool, mysql::Error> = Pool::new(state.driver.as_str());
    let pool: Pool;
    if let Ok(p) = pool_result {
        pool = p;
    } else {
        return "fail:无法建立数据库连接".to_string();
    }
    let conn_result: Result<PooledConn, mysql::Error> = pool.get_conn();
    let mut conn: PooledConn;
    if let Ok(c) = conn_result {
        conn = c;
    } else {
        return "fail:无法获取数据库连接".to_string();
    }

    let now: SystemTime = SystemTime::now();
    let since_epoch_res = now.duration_since(UNIX_EPOCH);
    let since_epoch: Duration;
    if let Ok(d) = since_epoch_res {
        since_epoch = d;
    } else {
        return "fail:时间戳获取失败".to_string();
    }
    let timestamp = since_epoch.as_secs();
    let mut sql: String = "UPDATE `copywrite_order` SET `status` = 3, `is_lock` = 1, `update_datetime` = :update_datetime WHERE `id` = :id".to_string();
    let _ = conn.exec_drop(sql.clone(), params![
        "update_datetime" => timestamp,
        "id" => form.id
    ]);

    sql = format!("SELECT `id` FROM `tag_group` WHERE `type` = '{}' ORDER BY `id` ASC", form.topic_type.as_str());
    let rows: Vec<Row> = conn.query(sql.clone()).unwrap();
    let mut gid: isize = -1;
    let mut min: isize = -1;
    for row in rows {
        let _gid: usize = from_row(row);
        sql = format!("SELECT COUNT(`id`) AS `count` FROM `clip_order` WHERE `group_id` = {} AND `status` = 3", _gid);
        let count_row: Row = conn.query_first(sql.clone()).unwrap().unwrap();
        let count: usize = from_row(count_row);
        if min == -1 || min > count as isize {
            min = count as isize;
            gid = _gid as isize;
            if min == 0 {
                break;
            }
        }
    }

    sql = format!("SELECT `topic_id` FROM `copywrite_order` WHERE `id` = {} LIMIT 1", form.id);
    let row: Row = conn.query_first(sql.clone()).unwrap().unwrap();
    let topic_id: usize = from_row(row);
    sql = "INSERT INTO `clip_order`(`copywrite_id`, `dub_file`, `topic_id`, `status`, `group_id`, `get_user_id`, `update_datetime`, `refuse_reason`, `i_file_list`, `v_file_list`) VALUES(:id, :file_list, :topic_id, 0, :gid, 0, 0, '', '', '')".to_string();
    if let Err(_) = conn.exec_drop(sql.clone(), params![
        "id" => form.id,
        "file_list" => form.file_list.as_str(),
        "topic_id" => topic_id,
        "gid" => gid
    ]) {
        return "fail:剪辑订单创建失败".to_string();
    } else {
        return "success:".to_string();
    }
}

#[derive(FromForm)]
struct RefuseCopywrite {
    id: usize
}

#[post("/library/refuse_copywrite_order", data = "<form>")]
fn refuse_copywrite_order(form: Form<RefuseCopywrite>, cookies: Cookies, state: State<MySqlDriver>) -> String {
    let user_info: UserInfo = get_cookies(&cookies);
    if user_info.id == 0 {
        return "fail:您未登录，请先登录".to_string();
    }

    let now: SystemTime = SystemTime::now();
    let since_epoch_res = now.duration_since(UNIX_EPOCH);
    let since_epoch: Duration;
    if let Ok(d) = since_epoch_res {
        since_epoch = d;
    } else {
        return "fail:时间戳获取失败".to_string();
    }
    let timestamp = since_epoch.as_secs();

    let pool_result: Result<Pool, mysql::Error> = Pool::new(state.driver.as_str());
    let pool: Pool;
    if let Ok(p) = pool_result {
        pool = p;
    } else {
        return "fail:无法建立数据库连接".to_string();
    }
    let conn_result: Result<PooledConn, mysql::Error> = pool.get_conn();
    let mut conn: PooledConn;
    if let Ok(c) = conn_result {
        conn = c;
    } else {
        return "fail:无法获取数据库连接".to_string();
    }

    let sql: String = "UPDATE `copywrite_order` SET `status` = 1, `update_datetime` = :time WHERE `id` = :id".to_string();
    if let Err(_) = conn.exec_drop(sql.clone(), params![
        "time" => timestamp,
        "id" => form.id
    ]) {
        return "fail:数据更新失败".to_string();
    } else {
        return "success:".to_string();
    }
}

#[get("/examine_copywrite_order?<id>")]
fn examine_copywrite_order(id: usize, cookies: Cookies, state: State<MySqlDriver>) -> Response<'static> {
    let mut res = Response::new();
    res.set_header(ContentType::HTML);

    let user_info: UserInfo = get_cookies(&cookies);
    if user_info.id == 0 {
        let html: String = format!("您未登录，请先<a href=\"{}login\">登录</a>", state.base_url.as_str());
        res.set_sized_body(Cursor::new(html));
        return res;
    }

    // mod_id: String, 
    // mod_menu_open: String, 
    // sub_mod_id: String, 
    // page_title: String, 
    // title: String
    let header: String = get_header(
        "examine-mod".to_string(), 
        "examine-mod-menu-open".to_string(), 
        String::new(),
        "用户后台 - 文案订单".to_string(), 
        "文案订单".to_string(), &cookies,
        &state);

    let pool_result: Result<Pool, mysql::Error> = Pool::new(state.driver.as_str());
    let pool: Pool;
    if let Ok(p) = pool_result {
        pool = p;
    } else {
        res.set_sized_body(Cursor::new("无法建立数据库连接".to_string()));
        return res;
    }
    let conn_result: Result<PooledConn, mysql::Error> = pool.get_conn();
    let mut conn: PooledConn;
    if let Ok(c) = conn_result {
        conn = c;
    } else {
        res.set_sized_body(Cursor::new("无法获取数据库连接".to_string()));
        return res;
    }
    let sql: String = format!("SELECT `copy_o`.`title`, `t`.`movie_name`, `copy_o`.`requirement`, `tg`.`type` AS `topic_type`, `copy_o`.`word_file` FROM `copywrite_order` AS `copy_o` INNER JOIN `topic` AS `t` ON `t`.`id` = `copy_o`.`topic_id` INNER JOIN `tag_group` AS `tg` ON `tg`.`id` = `copy_o`.`group_id` WHERE `copy_o`.`id` = {} LIMIT 1", id);
    let row_op: Option<Row> = conn.query_first(sql.clone()).unwrap();
    let row: Row;
    if let None = row_op {
        res.set_sized_body(Cursor::new("不存在该订单".to_string()));
        return res;
    } else {
        row = row_op.unwrap();
    }
    let (title, movie_name, requirement, topic_type, word_file): (String, String, String, String, String) = from_row(row);
    let word_file_hostr: HoString = HoString::copy_string(word_file);
    let mut file_list: Vec<HoString> = word_file_hostr.split_str("|");
    let tar_file: HoString = file_list.remove(0);

    let mut down_div: String = String::new();
    if tar_file.length() != 0 {
        down_div.push_str(format!("<div>\
                              <a target=\"_blank\" href=\"{}uploads/{}\">下载</a>\
                            </div>", state.base_url.as_str(), tar_file.to_str()).as_str());
    }
    
    let mut src_vec: Vec<&[u8]> = Vec::new();
    let mut replace_vec: Vec<&[u8]> = Vec::new();

    let id_str: String = id.to_string();
    let footer_string: String = get_footer();
    src_vec.push("{header}".as_bytes());
    src_vec.push("{base_url}".as_bytes());
    src_vec.push("{id}".as_bytes());
    src_vec.push("{title}".as_bytes());
    src_vec.push("{movie_name}".as_bytes());
    src_vec.push("{requirement}".as_bytes());
    src_vec.push("{topic_type}".as_bytes());
    src_vec.push("{down_div}".as_bytes());
    src_vec.push("{footer}".as_bytes());
    replace_vec.push(header.as_bytes());
    replace_vec.push(state.base_url.as_bytes());
    replace_vec.push(id_str.as_bytes());
    replace_vec.push(title.as_bytes());
    replace_vec.push(movie_name.as_bytes());
    replace_vec.push(requirement.as_bytes());
    replace_vec.push(topic_type.as_bytes());
    replace_vec.push(down_div.as_bytes());
    replace_vec.push(footer_string.as_bytes());

    let mut page_str: HoString = HoFile::read_file_bytes("web/examine_copywrite_order.html");
    page_str = page_str.replace_bytes_vec(src_vec, replace_vec);
    let html: String = page_str.to_str().to_string().to_owned();
    res.set_sized_body(Cursor::new(html));
    return res;
}

#[get("/examine_clip_order?<id>")]
fn examine_clip_order(id: usize, cookies: Cookies, state: State<MySqlDriver>) -> Response<'static> {
    let mut res = Response::new();
    res.set_header(ContentType::HTML);

    let user_info: UserInfo = get_cookies(&cookies);
    if user_info.id == 0 {
        let html: String = format!("您未登录，请先<a href=\"{}login\">登录</a>", state.base_url.as_str());
        res.set_sized_body(Cursor::new(html));
        return res;
    }

    // mod_id: String, 
    // mod_menu_open: String, 
    // sub_mod_id: String, 
    // page_title: String, 
    // title: String
    let header: String = get_header(
        "examine-mod".to_string(), 
        "examine-mod-menu-open".to_string(), 
        String::new(),
        "用户后台 - 剪辑订单".to_string(), 
        "剪辑订单".to_string(), &cookies,
        &state);

    let pool_result: Result<Pool, mysql::Error> = Pool::new(state.driver.as_str());
    let pool: Pool;
    if let Ok(p) = pool_result {
        pool = p;
    } else {
        res.set_sized_body(Cursor::new("无法建立数据库连接".to_string()));
        return res;
    }
    let conn_result: Result<PooledConn, mysql::Error> = pool.get_conn();
    let mut conn: PooledConn;
    if let Ok(c) = conn_result {
        conn = c;
    } else {
        res.set_sized_body(Cursor::new("无法获取数据库连接".to_string()));
        return res;
    }
    let sql: String = format!("SELECT `t`.`movie_name`, `copy_o`.`title`, `clip_o`.`i_file_list`, `clip_o`.`v_file_list`, `tg`.`type` AS `topic_type` FROM `clip_order` AS `clip_o` INNER JOIN `copywrite_order` AS `copy_o` ON `copy_o`.`id` = `clip_o`.`copywrite_id` INNER JOIN `topic` AS `t` ON `t`.`id` = `copy_o`.`topic_id` INNER JOIN `tag_group` AS `tg` ON `tg`.`id` = `copy_o`.`group_id` WHERE `clip_o`.`id` = {} LIMIT 1", id);
    let row_op: Option<Row> = conn.query_first(sql.clone()).unwrap();
    let row: Row;
    if let None = row_op {
        res.set_sized_body(Cursor::new("不存在该订单".to_string()));
        return res;
    } else {
        row = row_op.unwrap();
    }
    let (movie_name, title, i_file_list, v_file_list, topic_type): (String, String, String, String, String) = from_row(row);

    let i_file_list_hostr: HoString = HoString::copy_string(i_file_list);
    let i_file_array: Vec<HoString> = i_file_list_hostr.split_str("|");
    let mut i_file_html: String = String::new();
    for i_file_item in i_file_array {
        if i_file_item.length() == 0 {
            continue;
        }
        i_file_html.push_str(format!("<div>\
                                  <a href=\"{}uploads/{}\" download=\"{}\">{}下载</a>\
                            </div>", state.base_url.as_str(), i_file_item.to_str(), i_file_item.to_str(), i_file_item.to_str()).as_str());
    }

    let v_file_list_hostr: HoString = HoString::copy_string(v_file_list);
    let v_file_array: Vec<HoString> = v_file_list_hostr.split_str("|");
    let mut v_file_html: String = String::new();
    for v_file_item in v_file_array {
        if v_file_item.length() == 0 {
            continue;
        }
        v_file_html.push_str(format!("<div>\
                                  <a href=\"{}uploads/{}\" download=\"{}\">{}下载</a>\
                            </div>", state.base_url.as_str(), v_file_item.to_str(), v_file_item.to_str(), v_file_item.to_str()).as_str());
    }

    let mut src_vec: Vec<&[u8]> = Vec::new();
    let mut replace_vec: Vec<&[u8]> = Vec::new();

    let id_str: String = id.to_string();
    let footer_string: String = get_footer();
    src_vec.push("{header}".as_bytes());
    src_vec.push("{base_url}".as_bytes());
    src_vec.push("{id}".as_bytes());
    src_vec.push("{i_file_html}".as_bytes());
    src_vec.push("{v_file_html}".as_bytes());
    src_vec.push("{title}".as_bytes());
    src_vec.push("{movie_name}".as_bytes());
    src_vec.push("{topic_type}".as_bytes());
    src_vec.push("{footer}".as_bytes());
    replace_vec.push(header.as_bytes());
    replace_vec.push(state.base_url.as_bytes());
    replace_vec.push(id_str.as_bytes());
    replace_vec.push(i_file_html.as_bytes());
    replace_vec.push(v_file_html.as_bytes());
    replace_vec.push(title.as_bytes());
    replace_vec.push(movie_name.as_bytes());
    replace_vec.push(topic_type.as_bytes());
    replace_vec.push(footer_string.as_bytes());

    let mut page_str: HoString = HoFile::read_file_bytes("web/examine_clip_order.html");
    page_str = page_str.replace_bytes_vec(src_vec, replace_vec);
    let html: String = page_str.to_str().to_string().to_owned();
    res.set_sized_body(Cursor::new(html));
    return res;
}

#[derive(FromForm)]
struct AcceptClip {
    id: usize
}

#[post("/library/accept_clip_order", data = "<form>")]
fn accept_clip_order(form: Form<AcceptClip>, _cookies: Cookies, state: State<MySqlDriver>) -> String {
    let pool_result: Result<Pool, mysql::Error> = Pool::new(state.driver.as_str());
    let pool: Pool;
    if let Ok(p) = pool_result {
        pool = p;
    } else {
        return "fail:无法建立数据库连接".to_string();
    }
    let conn_result: Result<PooledConn, mysql::Error> = pool.get_conn();
    let mut conn: PooledConn;
    if let Ok(c) = conn_result {
        conn = c;
    } else {
        return "fail:无法获取数据库连接".to_string();
    }

    let now: SystemTime = SystemTime::now();
    let since_epoch_res = now.duration_since(UNIX_EPOCH);
    let since_epoch: Duration;
    if let Ok(d) = since_epoch_res {
        since_epoch = d;
    } else {
        return "fail:时间戳获取失败".to_string();
    }
    let timestamp = since_epoch.as_secs();
    let mut sql: String = format!("SELECT `gt`.`id` FROM `group_topic` AS `gt` INNER JOIN `clip_order` AS `clip_o` ON `clip_o`.`group_id` = `gt`.`group_id` AND `clip_o`.`topic_id` = `gt`.`topic_id` WHERE `clip_o`.`id` = {} LIMIT 1", form.id);
    let row_op: Option<Row> = conn.query_first(sql.clone()).unwrap();
    let row: Row;
    if let Some(r) = row_op {
        row = r;
    } else {
        return "fail:剪辑订单的小组选题不存在".to_string();
    }
    let id: usize = from_row(row);

    sql = format!("UPDATE `group_topic` SET `status` = 1 WHERE `id` = {}", id);
    let _ = conn.exec_drop(sql.clone(), ());
    sql = format!("UPDATE `clip_order` SET `status` = 3, `update_datetime` = {} WHERE `id` = {}", timestamp, form.id);
    let _ = conn.exec_drop(sql.clone(), ());
    return "success:".to_string();
}

#[derive(FromForm)]
struct RefuseClip {
    id: usize
}

#[post("/library/refuse_clip_order", data = "<form>")]
fn refuse_clip_order(form: Form<RefuseClip>, _cookies: Cookies, state: State<MySqlDriver>) -> String {
    let pool_result: Result<Pool, mysql::Error> = Pool::new(state.driver.as_str());
    let pool: Pool;
    if let Ok(p) = pool_result {
        pool = p;
    } else {
        return "fail:无法建立数据库连接".to_string();
    }
    let conn_result: Result<PooledConn, mysql::Error> = pool.get_conn();
    let mut conn: PooledConn;
    if let Ok(c) = conn_result {
        conn = c;
    } else {
        return "fail:无法获取数据库连接".to_string();
    }

    let now: SystemTime = SystemTime::now();
    let since_epoch_res = now.duration_since(UNIX_EPOCH);
    let since_epoch: Duration;
    if let Ok(d) = since_epoch_res {
        since_epoch = d;
    } else {
        return "fail:时间戳获取失败".to_string();
    }
    let timestamp = since_epoch.as_secs();
    let sql: String = format!("UPDATE `clip_order` SET `status` = 1, `update_datetime` = {} WHERE `id` = {}", timestamp, form.id);
    let _ = conn.exec_drop(sql.clone(), ());
    return "success:".to_string();
}

